package cn.leaf.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 *
 * description: 消息投递确认回执，手动消息确认确保消息成功投递
 *
 * @author Cyril
 * @version v1.0.0
 * @since 2021-05-20 21:44:47
 *
 */
@Component
@Slf4j
public class RabbitConfirmCallBack {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void orderMqCallBack() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                // ack ---> true：消息投递成功
                log.info("ack ---> {}", ack);
                log.info("cause ---> {}", cause);
                String msgId = correlationData.getId();

                // 1. 如果消息投递不成功
                if (!ack) {
                    log.error("消息投递失败，消息id ---> {}", msgId);
                    // 2. TODO 查询数据库消息冗余表投递状态为0的消息，定时重新投递
                    return;
                }

                // 3. 消息投递成功
                log.info("消息成功投递了...");
                // 4. TODO 修改数据库消息冗余表修改投递状态为1
            }
        });
    }
}